package com.hanhanxiaochong.zhongxiangchuanmei.view.my.act;

import android.content.Context;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShoppingCartItemBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.ShoppingCartPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.DensityUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IShoppingCartView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act.PayDetailActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.adapter.ShoppingCartAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.checkbox.SmoothCheckBox;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class ShoppingCartActivity extends BaseActivity<ShoppingCartPresenter> implements IShoppingCartView {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_go_to_shopping)
    TextView tvGoToShopping;
    @BindView(R.id.fl_mid)
    FrameLayout flMid;
    @BindView(R.id.cb_select_all)
    SmoothCheckBox cbSelectAll;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_select_total_money)
    TextView tvSelectTotalMoney;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.cl_empty_shopping_cart)
    ConstraintLayout clEmptyShoppingCart;

    private String token;
    private ShoppingCartAdapter adapter;
    private List<ShoppingCartItemBean> list;
    private double selectPrice;
    private StringBuilder shopping_id = new StringBuilder();
    private StringBuilder good_num = new StringBuilder();

    public static Intent createIntent(Context context) {
        return new Intent(context, ShoppingCartActivity.class);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_shopping_cart);
        EventBus.getDefault().register(this);
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ShoppingCartPresenter(this);
    }

    @Override
    protected void init() {
        mPresenter.getShoppingCartData(token);
        ViewGroup.LayoutParams layoutParams1 = cbSelectAll.getLayoutParams();
        layoutParams1.width = DensityUtil.dip2px(20, mContext);
        layoutParams1.height = DensityUtil.dip2px(20, mContext);
        cbSelectAll.requestLayout();

        cbSelectAll.setOnToggleClickListener(isChecked -> {
            selectPrice = 0;
            shopping_id = new StringBuilder();
            good_num = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                ShoppingCartItemBean bean = list.get(i);
                List<ShoppingCartItemBean.ListBean> beanList = bean.getList();
                bean.setSelected(cbSelectAll.isChecked());
                for (int j = 0; j < beanList.size(); j++) {
                    ShoppingCartItemBean.ListBean listBean = beanList.get(j);
                    if (isChecked) {
                        if (j == beanList.size() - 1 && i == list.size() - 1) {
                            shopping_id.append(listBean.getId());
                            good_num.append(listBean.getShop_num());
                        } else {
                            shopping_id.append(listBean.getId()).append(",");
                            good_num.append(listBean.getShop_num()).append(",");
                        }
                    }
                    listBean.setSelected(cbSelectAll.isChecked());
                    selectPrice += Double.parseDouble(listBean.getPrice_vip()) * Double.parseDouble(listBean.getShop_num());
                }
            }
            adapter.setDatas(list);
            if (isChecked) {
                tvOrder.setSelected(true);
                tvOrder.setClickable(true);
            } else {
                tvOrder.setSelected(false);
                tvOrder.setClickable(false);
            }

            tvSelectTotalMoney.setText(String.format(ResourcesUtils.getString(R.string.money),
                    new DecimalFormat("0.00").format(selectPrice)));
        });

        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        list = new ArrayList<>();
        adapter = new ShoppingCartAdapter(this, R.layout.item_shopping_cart_container, list);
        recyclerview.setAdapter(adapter);
        adapter.setOnGoodSelectListener(() -> {
            selectPrice = 0;
            shopping_id = new StringBuilder();
            good_num = new StringBuilder();
            List<ShoppingCartItemBean.ListBean> selectList = adapter.getSelectList();
            if (selectList.size() > 0) {
                tvOrder.setSelected(true);
                tvOrder.setClickable(true);
            } else {
                tvOrder.setSelected(false);
                tvOrder.setClickable(false);
            }
            appendString(selectList);
            tvSelectTotalMoney.setText(String.format(ResourcesUtils.getString(R.string.money),
                    new DecimalFormat("0.00").format(selectPrice)));
        });
        adapter.setOnMoneyChangedListener(() -> {
            selectPrice = 0;
            good_num = new StringBuilder();
            List<ShoppingCartItemBean.ListBean> selectList = adapter.getSelectList();
            for (ShoppingCartItemBean.ListBean bean : selectList) {
                good_num.append(bean.getShop_num()).append(",");
                selectPrice += Double.parseDouble(bean.getPrice_vip()) * Double.parseDouble(bean.getShop_num());
                tvSelectTotalMoney.setText(String.format(ResourcesUtils.getString(R.string.money),
                        new DecimalFormat("0.00").format(selectPrice)));
            }
        });
    }

    private void appendString(List<ShoppingCartItemBean.ListBean> selectList) {
        for (int i = 0; i < selectList.size(); i++) {
            ShoppingCartItemBean.ListBean bean = selectList.get(i);
            if (i == selectList.size() - 1) {
                shopping_id.append(bean.getId());
                good_num.append(bean.getShop_num());
            } else {
                shopping_id.append(bean.getId()).append(",");
                good_num.append(bean.getShop_num()).append(",");
            }
            selectPrice += Double.parseDouble(bean.getPrice_vip()) * Double.parseDouble(bean.getShop_num());
        }
    }

    @OnClick({R.id.tv_order, R.id.tv_edit, R.id.tv_delete,R.id.cl_empty_shopping_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_order:
                startActivity(PayDetailActivity.createIntent(this, null, null, shopping_id.toString(), good_num.toString()));
                break;
            case R.id.tv_edit:
                break;
            case R.id.tv_delete:
                break;
            case R.id.cl_empty_shopping_cart:
                MessageEvent messageEvent = new MessageEvent("shopping_cart");
                EventBus.getDefault().post(messageEvent);
                finish();
                break;
        }
    }

    @Override
    public void setShoppingCartData(List<ShoppingCartItemBean> data) {
        list = data;
        clEmptyShoppingCart.setVisibility(data.size() > 0 ? View.GONE : View.VISIBLE);
        llBottom.setVisibility(data.size() > 0 ? View.VISIBLE : View.GONE);
        recyclerview.setVisibility(data.size() > 0 ? View.VISIBLE : View.GONE);
        for (ShoppingCartItemBean bean : data) {
            if (bean.getC_name() == null)
                bean.setC_name("总店");
        }
        adapter.setDatas(data);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event){
        if (event.getMessage().equals("pay_success")){
            finish();
        }
    }
}
